﻿using AutoMapper;
using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Domain.PM;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using FarmSmartSleep.Organ.API.Application.AutoMapper;
using MediatR;
using System.Transactions;

namespace FarmSmartSleep.Organ.API.Application.ProductionManagement.MotherHybridizationCommands
{
    public class MotherHybridizationCreateHander : IRequestHandler<MotherHybridizationCreateCommand, Result>
    {

        private readonly ILogger<MotherHybridizationCreateHander> logger;
        private readonly IBaseRepository<MotherHybridization> MotherHybrizationRepository;
        private readonly IBaseRepository<SleepInfor> sleepInforRepository;
        private readonly IMapper mapper;

        public MotherHybridizationCreateHander(ILogger<MotherHybridizationCreateHander> logger, IBaseRepository<MotherHybridization> motherHybrizationRepository, IBaseRepository<SleepInfor> sleepInforRepository, IMapper mapper)
        {
            this.logger = logger;
            MotherHybrizationRepository = motherHybrizationRepository;
            this.sleepInforRepository = sleepInforRepository;
            this.mapper = mapper;
        }
        /// <summary>
        /// 种母配种
        /// </summary>
        /// <param name="request">种母配种方法请求对象</param>
        /// <param name="cancellationToken"></param>
        /// <returns>种母配种响应对象</returns>
        public async Task<Result> Handle(MotherHybridizationCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result();
            try
            {
                request.Datas.ForEach(c =>
                {
                    c.CreateTime = DateTime.Now;
                });
                result.Code = await MotherHybrizationRepository.AddRange(request.Datas);
                if (result.Code > 0)
                {
                    int n = 0;
                    request.Datas.ForEach(data =>
                    {
                        var info = sleepInforRepository.GetAll().FirstOrDefault(c => c.SleepInforId == data.MotherSleepInforId);
                        info.BreedStatuId = 6;
                         n += sleepInforRepository.Update(info);
                    });

                    if (result.Code != n)
                    {
                        result.Code = -1;
                    }
                    return result;
                }
                else
                {
                    result.Code = -1;
                    return result;
                }


            }
            catch (Exception ex )
            {
                logger.LogError("种母配种信息添加方法调用失败" + ex);
                throw;
            }
        }
    }
}
